package com.example.star.view.center;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

import com.bumptech.glide.Glide;
import com.example.star.R;
import com.example.star.api_service.ApiPerimeter;
import com.example.star.api_service.ApiUser;
import com.example.star.entity.Perimeter;
import com.example.star.entity.User;
import com.example.star.retrofit.ApiClient;
import com.example.star.utils.ImageUploadUtils;
import com.example.star.utils.ImageZoomDialogFragment;

import java.io.File;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ChangeAvatarActivity extends AppCompatActivity {

    private ImageView ivAvatar;
    private Button publishButton;
    private Button selectButton;
    private ImageUploadUtils imageUploadUtils;
    private String selectedImagePath;
    private String username; // 用于存储用户名

    private static final String TAG = "ChangeAvatarActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 加载自定义布局
        setContentView(R.layout.activity_change_avatar);

        // 从 SharedPreferences 中读取用户名
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        username = sharedPreferences.getString("username", "");
        getAndDisplayUserInfo(username);

        // 初始化视图
        ivAvatar = findViewById(R.id.iv_avatar);
        selectButton = findViewById(R.id.btn_select);
        publishButton = findViewById(R.id.btn_publish);

        // 初始化 ImageUploadUtils
        imageUploadUtils = new ImageUploadUtils(this, ivAvatar);

        // 设置点击事件监听器
        setupClickListeners();
    }
    private void getAndDisplayUserInfo(String username) {
        ApiUser apiUser = ApiClient.getApiUser();
        apiUser.getUserByUsername(username).enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful() && response.body() != null) {
                    User user = response.body();

                    //获取图片
                    Glide.with(ChangeAvatarActivity.this)
                            .load(user.getAvatar())
                            .placeholder(R.drawable.register)
                            .error(R.drawable.register)
                            .into(ivAvatar);

                    // 设置头像点击监听器
                    ivAvatar.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String imageUrl = user.getAvatar();
                            ImageZoomDialogFragment dialogFragment = ImageZoomDialogFragment.newInstance(imageUrl);
                            FragmentManager fragmentManager = getSupportFragmentManager();
                            dialogFragment.show(fragmentManager, "image_zoom_dialog");
                        }
                    });
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Toast.makeText(ChangeAvatarActivity.this, "加载信息失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        // 当从选择头像页面回来
        setupClickListeners();
    }

    private void setupClickListeners() {

        selectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageUploadUtils.startImageUpload();
            }
        });

        // 设置发布按钮点击事件
        publishButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取用户输入的信息
                String avatar = selectedImagePath;

                // 创建 Perimeter 对象
                User user = new User(avatar);
                // 发送 POST 请求保存到服务器
                sendPostRequest(user);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        imageUploadUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        imageUploadUtils.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        selectedImagePath = imageUploadUtils.getSelectedImagePath();
    }

    private void sendPostRequest(User user) {
        String Avatar = selectedImagePath;

        String originalUsername = getSharedPreferences("user_info", MODE_PRIVATE)
                .getString("username", "");

        ApiUser apiUser = ApiClient.getApiUser();
        Call<User> call = apiUser.changeAvatar(originalUsername, Avatar);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                int statusCode = response.code();
                Log.d(TAG, "Response status code: " + statusCode);
                if (response.isSuccessful()) {
                    Toast.makeText(ChangeAvatarActivity.this, "更新成功", Toast.LENGTH_SHORT).show();
                    // 发布成功后返回 HomeFragment
                    finish();
                } else {
                    try {
                        String errorBody = response.errorBody().string();
                        Log.d(TAG, "Response error body: " + errorBody);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(ChangeAvatarActivity.this, "更新失败，状态码: " + statusCode, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(ChangeAvatarActivity.this, "更新失败，网络请求出错: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}